import 'dart:io';
import 'dart:isolate';

void main() {
  print("main isolate start");
  multiThread();
  print("main isolate stop");
}

void multiThread() async {
  print("multiThread isolate start");
  //构建一个接受端口
  ReceivePort r1 = ReceivePort();
  SendPort sp1 = r1.sendPort;

  Isolate.spawn(newThread, sp1);

  SendPort p2 = await r1.first;

  var msg = await sendToReceive(p2, "main to child!");
  print("main接受到消息：$msg");
  print("multiThread isolate end");
}

void newThread(SendPort p1) async{
  ReceivePort receivePort = ReceivePort();
  p1.send(receivePort.sendPort);
  await for(var msg in receivePort){
    var data = msg[0];
    SendPort sendPort = msg[1];
    print("接收到主线程消息：$data");
    sendPort.send("this child msg");
  }


}

Future? sendToReceive(SendPort sendPort, msg) {
  print("要发送的消息：$msg");
  ReceivePort receive = ReceivePort();
  sendPort.send([msg, receive.sendPort]);
  return receive.first;
}
